package cn.wolfcode.luowowo.commment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.commment.repository.IStrategyCommentRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;


import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private IStrategyCommentRepository strategyCommentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IStrategyCommentRepository repository;


    @Override
    public void save(StrategyComment comment) {
        if (!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }
        strategyCommentRepository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //repository mongoTemplale 无法直接查询出page分页数据对象,需要自己手动封装
        //拼接条件
        Query query = new Query();
        if(qo.getDetailId()!=-1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //查询总条数
        long total = mongoTemplate.count(query, StrategyComment.class);
        if(total==0){
            return Page.empty();//返回空对象
        }
        //查询当前页显示list
        //注意需要设置分页信息以及排序信息
        //参数1:当前页,从0开始
        //参数2:每页显示的条数
        //参数3:排序规则
        //参数4:排序的字段
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(),
                Sort.Direction.DESC,"createTime");
        query.with(pageable);
        List<StrategyComment> list = mongoTemplate.find(query, StrategyComment.class);
        return new PageImpl(list,pageable,total);
    }

    @Override
    public void commentThumbUp(String detailId, Long userId) {
        StrategyComment comment = repository.findById(detailId).get();
        List<Long> list = comment.getThumbuplist();
        //当请求过来时判断点赞用户集合中是否包含登陆用户
        if(!list.contains(userId)){
            //如果不包含,则点赞数增加一,点赞集合增加当前用户
            comment.setThumbupnum(comment.getThumbupnum()+1);
            list.add(userId);
        }else{
            //如果包含,则点赞数减少一,点赞集合减少当前用户
            comment.setThumbupnum(comment.getThumbupnum()-1);
            list.remove(userId);
        }
        repository.save(comment);
    }
}
